package top.byfree.jbyan.saber.controller

import cn.dev33.satoken.annotation.SaCheckPermission
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.validation.annotation.Validated
import org.springframework.web.bind.annotation.*
import top.byfree.jbyan.saber.bean.dto.FilterRoleDto
import top.byfree.jbyan.saber.bean.dto.RoleDto
import top.byfree.jbyan.saber.common.*
import top.byfree.jbyan.saber.exception.SaberServiceException
import top.byfree.jbyan.saber.service.RoleService

/**
 * 角色控制器
 *
 * @author jbyan
 * @since 25/3/2024
 */
@RestController
@RequestMapping("role")
class RoleController(
    @Autowired private val roleService: RoleService,
) {

    /**
     * 根据角色编号获取角色详细信息
     *
     * @param roleId 角色编号
     */
    @GetMapping("{roleId}")
    @SaCheckPermission("sys:role:cat")
    fun get(@PathVariable roleId: String) =
        roleService.getOne(roleId)?.let { ok(data = it) } ?: throw SaberServiceException("获取角色编号不存在")

    /**
     * 根据角色编号获取角色下权限列表
     */
    @GetMapping("perm/{roleId}")
    @SaCheckPermission("sys:role:cat")
    fun getPermList(
        @PathVariable roleId: String
    ) = ok(data = roleService.getPermList(roleId))

    /**
     * 分页条件获取用户列表
     *
     * @param size 每页数据个数
     * @param current 当前业
     */
    @PostMapping("page/{size}/{current}")
    @SaCheckPermission("sys:role:cat")
    fun page(
        @PathVariable size: Int,
        @PathVariable current: Int,
        @RequestBody filterRoleDto: FilterRoleDto,
    ) = ok(data = roleService.page(size, current, filterRoleDto))

    /**
     * 新增角色
     *
     * @param roleDto 角色请求实体
     */
    @PutMapping
    @SaCheckPermission("sys:role:add")
    fun add(@Validated(AddGroup::class) @RequestBody roleDto: RoleDto) = result(roleService.add(roleDto))

    /**
     * 修改角色信息
     *
     * @param roleDto 角色请求实体
     */
    @PostMapping("{roleId}")
    @SaCheckPermission("sys:role:update")
    fun update(
        @PathVariable roleId: String,
        @Validated(UpdateGroup::class) @RequestBody roleDto: RoleDto,
    ) = result(roleService.update(roleId, roleDto))

    /**
     * 逻辑删除角色信息
     *
     * @param roleId 角色编号
     */
    @DeleteMapping("{roleId}")
    @SaCheckPermission("sys:role:delete")
    fun delete(@PathVariable roleId: String) = result(roleService.delete(roleId))


    /**
     * 修改角色拥有权限
     *
     * @param roleId 角色编号
     * @param perms 权限编号列表
     */
    @PostMapping("perm/{roleId}")
    @SaCheckPermission("sys:role:perm")
    fun editPerm(
        @PathVariable roleId: String,
        @RequestBody perms: MutableList<String>
    ) : R<Unit> {
        roleService.editPerm(roleId, perms)
        return ok()
    }

}